#include "JsonSerialize.h"

std::string JsonGenerator::generateJson(const std::vector<std::vector<ObjectInfo>> &objectInfos, uint32_t time, int32_t typeCode) {

     json::value dataArray;
     try {

         for (size_t i = 0; i < objectInfos.size(); i++) {
            for (size_t j = 0; j < objectInfos[i].size(); j++) {

         	    json::value itemData;
                    itemData["confidence"] = json::value::number(objectInfos[i][j].confidence);
                    itemData["index"] = json::value::number(objectInfos[i][j].classId);
                    itemData["label"] = json::value::string(objectInfos[i][j].className);

                    itemData["location"]["left"] = json::value::number(objectInfos[i][j].x0);
                    itemData["location"]["top"] = json::value::number(objectInfos[i][j].y0);
                    itemData["location"]["width"] = json::value::number(objectInfos[i][j].x1 - objectInfos[i][j].x0);
                    itemData["location"]["height"] = json::value::number(objectInfos[i][j].y1 - objectInfos[i][j].y0);

                    itemData["modelKind"] = json::value::number(2);
                    itemData["name"] = json::value::string(objectInfos[i][j].className);
                    itemData["score"] = json::value::number(objectInfos[i][j].confidence);

                    itemData["x1"] = json::value::number(objectInfos[i][j].x0);
                    itemData["x2"] = json::value::number(objectInfos[i][j].x1);
                    itemData["y1"] = json::value::number(objectInfos[i][j].y0);
                    itemData["y2"] = json::value::number(objectInfos[i][j].y1);

            	    dataArray[dataArray.size()] = itemData;
#if 0
                    std::cout << " objectInfo-" << j;
                    std::cout << "      x0 is:" << objectInfos[i][j].x0;
                    std::cout << "      y0 is:" << objectInfos[i][j].y0;
                    std::cout << "      x1 is:" << objectInfos[i][j].x1;
                    std::cout << "      y1 is:" << objectInfos[i][j].y1;
                    std::cout << "      confidence is: " << objectInfos[i][j].confidence;
                    std::cout << "      classId is: " << objectInfos[i][j].classId;
                    std::cout << "      className is: " << objectInfos[i][j].className;
                    std::cout << std::endl;
#endif
            }
        }

        m_json["cost_ms"] = json::value::number(time);
        m_json["error_code"] = json::value::number(typeCode);
        m_json["results"] = dataArray;

    } catch (const std::exception& e) {
   	// 异常处理
	LogError << "object detection failed.";

        m_json["cost_ms"] = json::value::number(time);
        m_json["error_code"] = json::value::number(-1);
        m_json["results"] = dataArray;
    }

    return m_json.serialize();
}

